#include "stdafx.h"
#include "cfixedframe.h"

CFixedFrameRate::CFixedFrameRate(int frameRate)
{
	m_frameRate = frameRate;
	QueryPerformanceCounter((LARGE_INTEGER*)&m_c0);
}
CFixedFrameRate::~CFixedFrameRate()
{
}
double CFixedFrameRate::getFrameLenght()
{
	return 1.0/(double)m_frameRate;
}
void CFixedFrameRate::endFrame()
{
	// entero de 64 bits (long int)
	__int64 m_c1, m_c, cps;
	double counter_duration,elapse_time,freq, s_dur, s_time;

	QueryPerformanceCounter((LARGE_INTEGER*)&m_c1);
	m_c = m_c1 - m_c0;

	// numero de veces que se actualiza el contador por seg (si devuelve 1000, hacemos 1 entre 1000 y nos devuelve un tiempo que tarda en contar 1)
	QueryPerformanceFrequency((LARGE_INTEGER*)&cps);
	counter_duration = (1.0/(double)cps);

	elapse_time = ((double)(m_c*counter_duration))*1000;

	s_dur = getFrameLenght()*1000;
	s_time = s_dur - elapse_time;

	if(s_time < 0) s_time = 0;
	Sleep((DWORD)s_time);
	QueryPerformanceCounter((LARGE_INTEGER*)&m_c0);
}